class Runner < ActiveRecord::Base

  belongs_to :group
  has_one :user
  has_many :entries

  validates_presence_of :group_id
  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_numericality_of :goal
  validates_numericality_of :shoe_size, :message => "must be a number."
  validates_inclusion_of :gender, :in => %w{ M F }, :message => "must be male or female (M/F)"

  after_save :update_caches_for_group
  after_destroy :update_caches_for_group
  after_update :update_caches_for_group
  
  def name
    "#{first_name} #{last_name}"
  end

  def percent_complete
    return calc_percent_complete(distance_cache, goal)
  end

  def update_caches!
    distance = 0
    sessions = 0
    entries.each do |entry|
      distance = distance + entry.distance
      sessions = sessions + entry.sessions
    end
    self.distance_cache = distance
    self.sessions_cache = sessions
    self.save!
    logger.debug{">>> UPDATED CACHES FOR RUNNER: #{name}"}
  end

  def has_login?
	  not self.user.nil?
  end

  def login_message
	  if self.has_login?
		self.user.login
	  else
		"No Login Information Found."
	  end
  end

  def current_route
	  self.group.site.routes[self.index_route]
  end

  # which route am I on?
  # i.e., 0, 1, 2, etc
  #    (for 1st, 2nd, 3rd, etc)
  def index_route
	  (self.distance_cache / 26.2).to_i
  end

  def distance_along_route
	  (self.distance_cache) % 26.2
  end

  private

    def update_caches_for_group
      group.update_caches!
    end

end
